using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using MongoDB.Driver;
using Sustainalytics.ClientDW.Entities;

namespace Sustainalytics.Synchronization.Validation.Log
{
    public class CorporateDataLoader
    {
        private readonly IMongoCollection<CorporateData> mongoCollection;

        private readonly IDictionary<Guid, CorporateDataInfo> corporateDataDictionary =
            new Dictionary<Guid, CorporateDataInfo>();

        public CorporateDataLoader(IMongoCollection<CorporateData> mongoCollection)
        {
            this.mongoCollection = mongoCollection;
        }

        public Task LoadDataAsync(IEnumerable<Guid> companyGuids)
        {
            return mongoCollection.Find(company => companyGuids.Contains(company.Id))
                .Project(
                    x =>
                    new CorporateDataInfo
                        {
                            CompanyId = x.Id, CompanyName = x.CompanyName, CapitalIqId = x.CapitalIqId
                        })
                .ForEachAsync(
                    company =>
                        {
                            corporateDataDictionary.Add(company.CompanyId, company);
                        });
        }

        public CorporateDataInfo GetCorporateDataInfo(Guid companyId)
        {
            if (!corporateDataDictionary.ContainsKey(companyId))
            { // TODO: refactor this, only for knowing which rule is not configured correctly 
                return new CorporateDataInfo() { CompanyId = companyId, CompanyName = companyId.ToString() };
            }

            return corporateDataDictionary[companyId];
        }
    }
}